const { spawn } = require('child_process');
const iconvLite = require('iconv-lite');
const { wait, getLogger } = require('./utility');
const path = require('path')
const sd = require('silly-datetime');


const pidDict = {};

/**
 * 执行sh脚本
 *
 * @param id 脚本id
 * @param socket socket object
 */
/* eslint-disable no-underscore-dangle, no-await-in-loop */
exports.execute = async function (id, socket) {

  const filePath = id + ".sh";
  const currentLog = sd.format(new Date(), 'YYYY-MM-DD');
  if (!filePath) {
    // res.sendStatus(404);
    return;
  }
  console.log(`The script:${filePath} with ${id} begin execute`);
  // const readable = new Readable();
  // readable._read = () => { };
  // readable.pipe(res);
  while (pidDict[id]) {
    // readable.push('\nWaiting for another script request.');
    await wait(5000);
  }
  console.log('filePath', path.resolve(__dirname, `../sh/${filePath}`))
  const handle = spawn('sh', [path.resolve(__dirname, `../sh/${filePath}`)], {
    shell: true,
  });
  pidDict[id] = handle.pid;

  handle.stdout.on('data', (data) => {
    socket.emit('deploy', `\n${iconvLite.decode(data, 'utf-8')}`);
    getLogger(currentLog).log(`\n${data}`);
  });

  handle.stderr.on('data', (data) => {
    socket.emit('deploy', `\n${iconvLite.decode(data, 'utf-8')}`);
    getLogger(currentLog).warn(`${iconvLite.decode(data, 'utf-8')}`);
    // readable.push(`${iconvLite.decode(data, 'cp936')}`);
  });

  handle.on('error', (code) => {
    socket.emit('deploy', `\n${code}`);
    getLogger(currentLog).error(`child process error with information: \n${handle.pid}`);
    delete pidDict[id];

  });

  handle.on('close', (code) => {
    socket.emit('deploy', `\n${code}`);
    getLogger(currentLog).log(`child process close with code ${handle.pid}`);
    delete pidDict[id];
  });
}